/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Main.java
 *
 * Created on 04.09.2010, 21:47:07
 */
package university.kuzenko.ui;

import java.io.IOException;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import university.kuzenko.client.DatabaseFactory;
import university.kuzenko.db.AttributeType;
import university.kuzenko.db.DataBase;
import university.kuzenko.db.DataBases;
import university.kuzenko.db.DoubleInterval;
import university.kuzenko.db.Row;
import university.kuzenko.db.Table;
import university.kuzenko.db.TableHeader;

/**
 *
 * @author taras
 */
public class Main extends javax.swing.JFrame {

    Table table;
    DataBase db;
    DataBases dbs;
    DatabaseFactory.Type type = DatabaseFactory.Type.DIRECT;

    /** Creates new form Main */
    public Main() {
        initComponents();
        dbs = DatabaseFactory.getDatabases(type);
        refreshDBS();
        grid.setCellSelectionEnabled(true);
       
    }

    public void refreshDBS() {
        databases.setModel(new DefaultComboBoxModel(dbs.getNames()));
        refreshDB();
    }

    public void refreshDB() {
        db = DatabaseFactory.getDatabase(type, databases.getSelectedItem().toString());
        tables.setModel(new DefaultComboBoxModel(db.getTableNames()));
        refreshTable();
    }

    public void saveRow(int i) {
        Row r = table.getRow(i);
        for (int j = 0; j < r.size(); j++) {
            Object o=null;
            String go = grid.getValueAt(i, j).toString();
            AttributeType type = table.getHeader().getTypes().get(j);
            try {
                switch (type) {
                    case CHAR: {
                        o = Character.valueOf(go.charAt(0));
                        break;
                    }
                    case INTEGER: {
                        o = Integer.valueOf(go);
                        break;
                    }
                    case PICTURE: {
                        o = go;
                        break;
                    }
                    case REAL: {
                        o = Double.valueOf(go);
                        break;
                    }
                    case REALINVL: {
                        o = DoubleInterval.valueOf(go);
                        break;
                    }
                }
            } catch (Exception e) {
                grid.setColumnSelectionInterval(j, j);
                grid.setRowSelectionInterval(i, i);
                JOptionPane.showMessageDialog(this, "bad value");
                return;
            }
            r.set(j, o);
        }
        table.setRow(i, r);
        try {
            db.save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void refreshTable() {
        table = db.getTable(tables.getSelectedItem().toString());
        Vector<String> names = new Vector(table.getHeader().getNames());
        grid.setModel(new DefaultTableModel(names, table.size()));
        Row[] rows = table.getRows(0, table.size());
        for (int i = 0; i < rows.length; i++) {
            Row row = rows[i];
            for (int j = 0; j < row.size(); j++) {
                Object object = row.get(j);
                grid.getModel().setValueAt(object, i, j);
            }
        }
         grid.getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                int row = e.getFirstRow();
                saveRow(row);
            }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        databases = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        createDBName = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        tables = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        grid = new javax.swing.JTable();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        databases.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                databasesActionPerformed(evt);
            }
        });

        jButton1.setText("create DB");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        createDBName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                createDBNameActionPerformed(evt);
            }
        });

        jButton2.setText("delete");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        tables.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tablesActionPerformed(evt);
            }
        });

        grid.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                gridMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(grid);

        jButton3.setText("new table");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setText("delete table");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("new row");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("save");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 666, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(tables, javax.swing.GroupLayout.PREFERRED_SIZE, 212, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(26, 26, 26)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton6)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tables, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4)
                    .addComponent(jButton5)
                    .addComponent(jButton3)
                    .addComponent(jButton6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(35, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(databases, javax.swing.GroupLayout.PREFERRED_SIZE, 402, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                        .addComponent(createDBName, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton1)
                        .addGap(18, 18, 18))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(databases, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)
                    .addComponent(createDBName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createDBNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createDBNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_createDBNameActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        dbs.delete(databases.getSelectedItem().toString());
        refreshDBS();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        dbs.create(createDBName.getText());
        refreshDBS();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void databasesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_databasesActionPerformed
        refreshDB();
    }//GEN-LAST:event_databasesActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        TableHeaderConstructor thc = new TableHeaderConstructor(this, true);
        TableHeader header = thc.getHeader();
        String name = thc.getTableName();
        if (thc.isOk) {
            db.createTable(name, header);
            refreshDB();
        }
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        db.deleteTable(tables.getSelectedItem().toString());
        refreshDB();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        table.addRow(new Row(table.getHeader()));
        refreshTable();
    }//GEN-LAST:event_jButton5ActionPerformed

    private void tablesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tablesActionPerformed
        refreshTable();
    }//GEN-LAST:event_tablesActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        try {
            db.save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_jButton6ActionPerformed

    private void gridMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_gridMouseClicked
        int x = grid.getSelectedColumn(),
                y = grid.getSelectedRow();
        Row r = table.getRow(y);
        if (table.getHeader().getTypes().get(x) == AttributeType.PICTURE) {
            PictureEdit pe = new PictureEdit(this, true);
            grid.setValueAt(pe.modifyPicture(r.get(x).toString()), y, x);

        }

    }//GEN-LAST:event_gridMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Main().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField createDBName;
    private javax.swing.JComboBox databases;
    private javax.swing.JTable grid;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox tables;
    // End of variables declaration//GEN-END:variables
}
